<template>
  <div id="wlinsertbyscancoderef">
    <el-dialog title="扫码上机" width="80vw" top="10vh" draggable destroy-on-close v-model="visible" v-if="visible"
      :close-on-click-modal="false" :before-close="beforeDlgclose">
      <div class="solid-bottom">
        <vxe-form :data="form">
          <vxe-form-item title="检测时间" span="4" field="sampleda">
            <vxe-input v-model="form.sampleda" type="date" :value-format="'yyyy-MM-dd'" :label-format="'yyyy-MM-dd'"
              clearable transfer @change="timeChange">
            </vxe-input>
          </vxe-form-item>
          <vxe-form-item field="sampleNo" title="标本号" span="5">
            <vxe-input v-model="form.sampleNo" placeholder="请输入内容" clearable @keydown="sampleNoKeydown"></vxe-input>
          </vxe-form-item>
          <vxe-form-item field="reqNo" title="条码号" span="5">
            <vxe-input ref="scanInputRef" v-model="form.reqNo" placeholder="请扫条码号" clearable @keydown="keyup"></vxe-input>
          </vxe-form-item>
          <vxe-form-item title span="5">
            <vxe-button @click="beforeDlgclose">退 出(ESC)</vxe-button>
          </vxe-form-item>
        </vxe-form>
      </div>
      <div class="scanTableBox">
        <vxe-table ref="tableScanCode" border :header-row-style="{ padding: '2px' }" :header-cell-style="{ padding: '0' }"
          :row-style="{ height: '0' }" :cell-style="{ padding: '0' }" v-loading="loading" max-height="400px" height="auto"
          :data="tableList" highlight-current-row empty-text="请输入名称搜索">
          <vxe-column title="序号" width="50" sortable>
            <template #default="{ row, rowIndex }">
              <span>{{ rowIndex + 1 }}</span>
              <span v-if="row.status === 'watting'" class="vxe-icon-repeat roll" style="color: gray"></span>
              <span v-if="row.status === 'doing'" class="vxe-icon-spinner roll vxe-loading--default-ico"
                style="color: green"></span>
              <span v-if="row.status === 'finish'" class="vxe-icon-success-circle-fill" style="color: orange"></span>
              <span v-if="row.status === 'coderepeat'" style="color: red">重</span>
              <span v-if="row.status === 'error'" class="vxe-icon-error-circle-fill" style="color: pink"></span>
            </template>
          </vxe-column>
          <vxe-column field="sampleNo" :title="'标本号'" width="60" align="left" show-overflow-tooltip></vxe-column>
          <vxe-column field="reqNo" :title="'申请号'" width="120" align="left" show-overflow-tooltip></vxe-column>
          <vxe-column field="patNa" :title="'姓名'" width="65" align="left" show-overflow-tooltip></vxe-column>
          <vxe-column field="reqDept" :title="'科室'" width="80" align="left" show-overflow-tooltip></vxe-column>
          <vxe-column field="sex" :title="'性别'" width="50" align="left" show-overflow-tooltip>
            <template #default="{ row }">{{ row.sex === '1' ? '男' : row.sex === '2' ? '女' : '未知' }}</template>
          </vxe-column>
          <vxe-column field="age" :title="'年龄'" width="50" align="left" show-overflow-tooltip></vxe-column>
          <vxe-column field="bedNo" :title="'床号'" width="60" align="left" show-overflow-tooltip></vxe-column>
          <vxe-column field="sampleTypeNa" :title="'样本类型'" width="70" align="left" show-overflow-tooltip></vxe-column>
          <vxe-column field="reqPurpose" :title="'检验目的'" min-width="200" align="left"></vxe-column>
          <vxe-column fixed="right" title="操作" width="70" align="center">
            <template #default="{ row, rowIndex }">
              <el-button @click="handleDeleteClick(row, rowIndex)" type="text" size="small">删除</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <span class="text-red text-bold">共【{{ tableList.length }}】个标本</span>
          <span></span>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, defineExpose, getCurrentInstance, onMounted } from 'vue';
import { IsEmpty, formatDateTime, DateToString, autoIncrementNumber } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { VXETable, VxeFormPropTypes, VxeFormInstance } from 'vxe-table';

let { proxy }: any = getCurrentInstance();
//绑定组织模块列表的数据
let tableList: any = reactive([]); //项目列表数据
let mainInfoList: any = reactive([]);
let visible = ref(false);
const loading = ref(false);
let scanCount = ref(0);
let form = reactive({
  rptGroup: '',
  wtName: '',
  sampleNo: '1',
  reqNo: '',
  sampleda: formatDateTime(new Date(), 'yyyy-MM-dd'),
  dataType: '1' /**业务类型，1普通检验   2微生物 */
});
defineExpose({
  wkltData,
  focus,
  updateLabMaininfoList /**更新检验记录列表 */
});

/**接收父组件传值 */
function wkltData(repData) {
  console.log('repData', repData);
  visible.value = true;
  if (IsEmpty(repData.id)) {
    form.sampleNo = repData.sampleNo;
  } else {

    if (repData.wl && repData.wl.length > 0) {


      let wlList = repData.wl.filter(item => item.sampleda == repData.sampleda);
      console.log('wlList', wlList);
      //取出wlList中的最后一条数据
      let lastWl = wlList[wlList.length - 1];
      console.log('lastWl', lastWl);
      form.sampleNo = autoIncrementNumber(lastWl.sampleNo, '+');

      // if (repData.dataType == '1') {
      //   let wlList = repData.wl.filter(item => item.sampleda == repData.sampleda);
      //   console.log('wlList', wlList);
      //   //取出wlList中的最后一条数据
      //   let lastWl = wlList[wlList.length - 1];
      //   console.log('lastWl', lastWl);
      //   form.sampleNo = autoIncrementNumber(lastWl.sampleNo, '+');
      // } else {
      //   //repData.wl 根据sampleda排序
      //   let wlList = repData.wl.sort((a, b) => {
      //     return new Date(a.sampleda).getTime() - new Date(b.sampleda).getTime();
      //   });
      //   console.log('wlList', wlList);
      //   let lastWl = wlList[wlList.length - 1];
      //   //判断lastWl的sampleda是不是今天的日期
      //   let dateNow = formatDateTime(new Date(), 'yyyy-MM-dd');

      //   console.log('repData.wl=========', lastWl.sampleda, dateNow);
      //   if (lastWl.sampleda == dateNow) {
      //     form.sampleNo = autoIncrementNumber(lastWl.sampleNo, '+');
      //   } else {
      //     form.sampleNo = formatDateTime(new Date(), 'yyMMdd') + '0001';
      //   }
      // }

    } else {
      const a = autoIncrementNumber(repData.sampleNo, '+');
      form.sampleNo = a;
    }
  }

  form.rptGroup = repData.rptGroup;
  form.sampleda = repData.sampleda;
  form.dataType = repData.dataType;

  // 多重保障
  proxy.$nextTick(() => {
    setTimeout(() => {
      const inputRef = proxy.$refs.scanInputRef;
      if (inputRef && inputRef.focus) {
        inputRef.focus();
      } else {
      }
    }, 200);
  });
}
function focus() {
  proxy.$nextTick(() => {
    (proxy.$refs.scanInputRef as any).focus();
  });
}
/**更新当前检验列表数组 */
function updateLabMaininfoList(arr) {
  mainInfoList.length = 0;
  Object.assign(mainInfoList, arr);
}
//?弹窗关闭前回调 (done)
function beforeDlgclose(done) {
  const isUnfinish = tableList.some((item) => {
    return item.status === 'watting' || item.status === 'doing';
  });
  if (isUnfinish) {
    proxy.$alert('请等待已扫条码完成上机...', '提示');
    return;
  }
  proxy.$emit('refreshLabMinInfo');
  tableList.length = 0;
  form.sampleNo = '';
  form.reqNo = '';
  scanCount.value = 0;
  visible.value = false;
}
function handleDeleteClick(row, idx) {
  if (row && !IsEmpty(row.id)) {
    const url = '/lab/maininfo/deleteMaininfoById';
    let params = {
      id: row.id,
      sampleda: row.sampleda,
      rptGroup: row.rptGroup,
      sampleNo: row.sampleNo
    };
    proxy.$http
      .post(url, params)
      .then((res: any) => {
        if (res.status.code == 1) {
          VxeMessage(res.status.msg, VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  }
  tableList.splice(idx, 1);
}
//监听回车事件
async function keyup(e: any) {
  if (e.$event.key == 'Enter') {
    /**验证是否错乱扫码 */
    const res = await validateByScanReqNo(form.reqNo);
    if (res && res.data === false) {
      const type = await VXETable.modal.alert({ content: res.status.msg, showCancelButton: false, escClosable: true, title: '提示' });
      if (type !== 'confirm' || type === 'confirm') {
        return;
      }
    }

    addWklt();
  }
}
/* 验证扫条码是否乱扫 */
function validateByScanReqNo(reqNo) {
  return new Promise((resolve, reject) => {
    const params = {
      reqNo: reqNo,
      rptGroup: form.rptGroup
    };
    const url = '/lab/maininfo/validateByScanReqNo';
    proxy.$http.get(url, { params: params }).then((res: any) => {
      return resolve(res);
    });
  });
}
//扫码回车事件
async function addWklt() {
  //?条码号为空，不添加
  if (IsEmpty(form.reqNo)) {
    form.reqNo = '';
    (proxy.$refs.scanInputRef as any).focus();
    return;
  }

  const reqNoList = await findLabMainInfoByReqNo(form.rptGroup, form.reqNo);
  if (reqNoList && reqNoList.length > 0) {
    let str = '';
    reqNoList.forEach((element) => {
      str += '→  报告单元：' + element.rptGroupNa + '\u0020\u0020\u0020\u0020上机日期：' + element.sampleda + '\u0020\u0020\u0020\u0020 条码号：' + element.sampleNo + '\n';
    });
    const type = await VXETable.modal.confirm(`条码被重复使用，相关标本如下：\n  ${str}`); /*不能改el  $confirm 回车事件冒泡你*/
    if (type === 'confirm') {
      //?条码号重复扫不添加
      const isSpmCode = tableList.some((item) => {
        return item.reqNo === form.reqNo;
      });
      if (isSpmCode) {
        //const type = await VXETable.modal.confirm('该标本号已有病人信息, 是否继续？'); /*不能改el  $confirm 回车事件冒泡*/
        //if (type === 'confirm') {
        form.reqNo = '';
        (proxy.$refs.scanInputRef as any).focus();
        return;
        // }
      }
    }
  }
  proxy.$emit('getLabMainInfos');
  //?标本号重复，添加，但不走保存
  let isCode = mainInfoList.some((item) => {
    return form.dataType === '2' ? item.reqNo === form.reqNo && formatDateTime(item.sampleda, 'yyyy-MM-dd') === formatDateTime(form.sampleda, 'yyyy-MM-dd') : item.reqNo === form.reqNo;
  });

  let statusStr = 'watting';
  if (isCode) {
    statusStr = 'coderepeat';
  } else {
    /**验证当前弹窗列表是有重复 */
    isCode = tableList.some((item) => {
      return item.reqNo === form.reqNo;
    });
    if (isCode) {
      statusStr = 'coderepeat';
    }
  }
  const data = {
    status: statusStr,
    sampleNo: form.sampleNo,
    reqNo: IsEmpty(form.reqNo) ? '' : form.reqNo.trim(),
    sampleda: IsEmpty(form.sampleda) ? formatDateTime(new Date(), 'yyyy-MM-dd') : formatDateTime(form.sampleda, 'yyyy-MM-dd'),
    rptGroup: form.rptGroup
  };
  tableList.push(data);
  const $reportTable = proxy.$refs.tableScanCode;
  if ($reportTable) {
    // $reportTable.setCurrentRow(data);
    proxy.$nextTick(() => {
      setTimeout(() => {
        $reportTable.scrollToRow(data);
      }, 150);
    });
  }
  saveWklts();
  const a = autoIncrementNumber(form.sampleNo, '+');
  form.sampleNo = a;
  form.reqNo = '';
  (proxy.$refs.scanInputRef as any).focus();
}

/**按条码号没有记录 */
function findLabMainInfoByReqNo(rptGroup, reqNo) {
  return new Promise((resolve, reject) => {
    const url = '/lab/maininfo/findLabMaininfoByReqNo';
    proxy.$http
      .get(url, { params: { reqNo: reqNo, rptGroup: rptGroup } })
      .then((res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && res.data && res.data.length > 0) {
          resolve(res.data);
        } else {
          resolve(null);
        }
      })
      .catch((err: any) => {
        resolve(null);
      });
  });
}

function testScan() {
  const arr = [];
  let i = 0;
  const interval = setInterval(() => {
    const val = arr[i];
    const data = {
      status: 'watting',
      sampleNo: form.sampleNo,
      reqNo: val,
      sampleda: IsEmpty(form.sampleda) ? formatDateTime(new Date(), 'yyyy-MM-dd') : formatDateTime(form.sampleda, 'yyyy-MM-dd'),
      wtName: form.wtName,
      rptGroup: form.rptGroup
    };
    tableList.push(data);
    saveWklts(i === arr.length - 1);
    if (i === arr.length - 1) {
      clearInterval(interval);
    }
    i++;
  }, 100);
}
//?提交数据
function saveWklts(isLastOne = false) {
  tableList.forEach((item, index) => {
    if (item.status === 'watting') {
      item.status = 'doing';
      const url = '/lab/maininfo/insertMaininfoByReqNo';
      const data = {
        rptGroup: form.rptGroup,
        sampleda: IsEmpty(form.sampleda) ? formatDateTime(new Date(), 'yyyy-MM-dd') : formatDateTime(form.sampleda, 'yyyy-MM-dd'),
        sampleNo: form.sampleNo,
        reqNo: IsEmpty(item.reqNo) ? '' : item.reqNo.trim(),
        dataType: form.dataType
      };
      //#region 默认添加记忆的检验者  审核者
      let approveConfirmObj = {} as any;
      try {
        const approveConfirm = sessionStorage.getItem('locChkDoctor');
        if (IsEmpty(approveConfirm)) {
          //todo
        } else {
          approveConfirmObj = JSON.parse(approveConfirm);
          //验证是否过期
          const curDateTime = new Date().valueOf();
          if (Number(curDateTime) <= Number(approveConfirmObj.expressin)) {
            const a = 'chkDoctor';
            data[a] = approveConfirmObj.code;
          }
        }
      } catch (error) {
        //todo
      }
      try {
        const approveConfirm = sessionStorage.getItem('locTestDoctor');
        if (IsEmpty(approveConfirm)) {
          //todo
        } else {
          approveConfirmObj = JSON.parse(approveConfirm);
          //验证是否过期
          const curDateTime = new Date().valueOf();
          if (Number(curDateTime) <= Number(approveConfirmObj.expressin)) {
            const a = 'testDoctor';
            data[a] = approveConfirmObj.code;
          }
        }
      } catch (error) {
        //todo
      }
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          if (res.status.code == 1) {
            item.status = 'finish';
            Object.assign(item, res.data);
            VxeMessage(res.status.msg, VxeNotifyType.success);
          } else {
            item.status = 'error';
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          item.status = 'error';
          VxeMessage(err, VxeNotifyType.error);
        });
      /*      this.axios
                .post(url, data)
                .then((res: any) => {
                  if (res) {
                    item.status = 'finish';
                    this.$emit('RefreshWklt', index === this.scanCount - 1);
      
                  }
                })
                .catch(err => {
                  item.status = 'error';
                  this.$alert(err.data.error.message, '提示');
                });*/
    }
  });
}
function sampleNoKeydown({ value, $event }: any) {
  if ($event.keyCode === 13) {
    if (!IsEmpty(value)) {
      (proxy.$refs.scanInputRef as any).focus();
    }
  }
}

function timeChange(val) {
  console.log('timeChange', val);

}


</script>
<style lang="scss" scoped>
@import '@/assets/css/isd-body.scss';

#wlinsertbyscancoderef {
  .el-dialog {
    max-height: 1000px;
  }

  .scanTableBox {
    height: 400px;
    margin-top: 10px;
  }

  :deep(.el-input__inner) {
    padding: 0 1px !important;
  }
}
</style>
